from django import http
from django.core.paginator import Paginator
from django.db.models.functions import datetime
from django.shortcuts import render

# Create your views here.
from django.utils import timezone
from django.views import View
import logging
from goods import cishu
from goods.models import GoodsLeibie, SKU, GoodsVisitCount
from goods.utils import get_categories, get_breadcrumb, get_goods_and_spec
from meiduo_mall.utils.response_code import RETCODE
logger = logging.getLogger('django')


class ListView(View):
    def get(self, request, category_id, page_num):
        try:
            category = GoodsLeibie.objects.get(id=category_id)
        except Exception as e:
            return http.HttpResponseForbidden('类别ID错误')

        categories = get_categories()

        breadcrumb = get_breadcrumb(category)

        sort = request.GET.get('sort', 'default')

        if sort == 'price':
            sortkind = 'price'

        elif sort == 'hot':
            sortkind = '-sales'

        else:
            sort = 'default'
            sortkind = 'create_time'

        skus = SKU.objects.filter(category=category, is_launched=True).order_by(sortkind)

        paginator = Paginator(skus, cishu.cishu5)
        try:
            page = paginator.page(page_num)
        except Exception as e:
            return http.HttpResponseNotFound('404')

        all_page = paginator.num_pages

        context = {
            'categories': categories,
            'breadcrumb': breadcrumb,
            'sort': sort,
            'category': category,
            'page_skus': page,
            'total_page': all_page,
            'page_num': page_num
        }

        return render(request, 'list.html', context)


class HotView(View):
    def get(self, request, category_id):
        # try:
        skus = SKU.objects.filter(id=category_id, is_launched=True).order_by('-sales')[:2]
        # except Exception as e:
        #     return http.HttpResponseForbidden('获取商品失败')

        hot_skus = []

        for sku in skus:
            hot_skus.append({
                'id': sku.id,
                'default_image_url': sku.default_image_url,
                'name': sku.name,
                'price': sku.price
            })

        return http.JsonResponse({'code': RETCODE.OK,
                                  'errmsg': 'ok',
                                  'hot_skus': hot_skus})


class DetailView(View):
    def get(self, request, sku_id):
        try:
            sku = SKU.objects.get(id=sku_id)
        except Exception as e:
            return render(request, '404.html')

        categories = get_categories()

        data = get_goods_and_spec(sku_id, request)

        breadcrumb = get_breadcrumb(data['goods'].category3)

        context = {
            'categories': categories,
            'goods': data.get('goods'),
            'specs': data.get('goods_specs'),
            'sku': data.get('sku'),
            'breadcrumb': breadcrumb
        }

        return render(request, 'detail.html', context)


class DetailVisitView(View):
    def post(self, request, category_id):
        try:
            category = GoodsLeibie.objects.get(id=category_id)
        except Exception as e:
            return http.HttpResponseForbidden('缺少必传参数')

        t = timezone.localtime()

        time_str = '%d-%02d-%02d' % (t.year, t.month, t.day)

        time_data = datetime.datetime.strptime(time_str, '%Y-%m-%d')

        try:
            counts = category.goodsvisitcount_set.get(date=time_data)
        except Exception as e:
            counts = GoodsVisitCount()

        try:
            counts.category = category
            counts.count += 1
            counts.save()
        except Exception as e:
            logger.error(e)
            return http.HttpResponseServerError('服务器出错')

        return http.JsonResponse({'code': RETCODE.OK,
                                  'errmsg': 'ok'})
